<template>
	<div class="user">
		<el-row class="searchForm" v-if="showSearch">
			<el-col>
				<el-form
					ref="searchForm"
					:model="searchForm"
					status-icon
					label-width="100px"
					size="mini"
					:inline="true"
				>
					<el-form-item label="用户名称" prop="username" class="form-item">
						<el-input
							v-model.trim="searchForm.username"
							placeholder="请输入用户名称"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="手机号码" prop="phone" class="form-item">
						<el-input
							v-model.trim="searchForm.phone"
							placeholder="请输入手机号码"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="状态" prop="status" class="form-item">
						<el-select v-model="searchForm.status" placeholder="用户状态" clearable>
							<el-option
								v-for="item in statusOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
								class="form-input"
							>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="创建时间" prop="createTimes" class="form-item">
						<el-date-picker
							v-model="searchForm.createTimes"
							type="daterange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="yyyy-MM-dd HH:mm:ss"
							class="form-input"
						>
						</el-date-picker>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<el-row style="padding-bottom: 20px">
			<el-col :push="1" :span="23">
				<el-button type="primary" size="mini" icon="el-icon-search" @click="search"
					>搜索</el-button
				>
				<el-button
					size="mini"
					icon="el-icon-refresh"
					@click="resetForm('searchForm')"
					v-if="showSearch"
					>重置
				</el-button>
			</el-col>
		</el-row>

		<el-row>
			<el-col :push="1" :span="20">
				<el-button plain type="primary" size="mini" icon="el-icon-plus" @click="create"
					>新增
				</el-button>
				<el-button
					size="mini"
					plain
					type="success"
					icon="el-icon-scissors"
					@click="update"
					:disabled="checkIds.length != 1"
					>修改
				</el-button>
				<el-button
					size="mini"
					plain
					type="danger"
					icon="el-icon-delete-solid"
					@click="remove"
					:disabled="checkIds.length == 0"
					>删除
				</el-button>
			</el-col>

			<el-col :push="1" :span="2">
				<el-tooltip effect="dark" content="隐藏搜索" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-search"
						@click="showSearch = !showSearch"
					>
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="刷新" placement="top">
					<el-button size="mini" circle icon="el-icon-refresh" @click="refresh">
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="隐藏列" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-menu"
						@click="showHidCol = !showHidCol"
					>
					</el-button>
				</el-tooltip>
				<el-popover width="60" placement="bottom" trigger="click" v-model="showHidCol">
					<el-checkbox-group v-model="checkedColumns">
						<el-checkbox v-for="column in columns" :label="column" :key="column">
						</el-checkbox>
					</el-checkbox-group>
				</el-popover>
			</el-col>
		</el-row>

		<el-row>
			<el-table
				ref="multipleTable"
				:data="list"
				tooltip-effect="dark"
				style="width: 100%"
				@selection-change="handMulSelect"
			>
				<el-table-column type="selection"> </el-table-column>
				<el-table-column
					prop="userId"
					label="用户编号"
					v-if="$Tool.findEle('用户编号', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="avatar"
					label="头像"
					v-if="$Tool.findEle('头像', checkedColumns)"
				>
					<template slot-scope="scope">
						<el-avatar size="large" :src="scope.row.avatar"></el-avatar>
					</template>
				</el-table-column>
				<el-table-column
					prop="username"
					label="用户名称"
					v-if="$Tool.findEle('用户名称', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="nickname"
					label="用户昵称"
					v-if="$Tool.findEle('用户昵称', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="phone"
					label="手机号码"
					v-if="$Tool.findEle('手机号码', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="sex"
					label="性别"
					v-if="$Tool.findEle('性别', checkedColumns)"
				>
					<template slot-scope="scope">
						<el-tag
							:type="
								scope.row.sex == '0'
									? 'primary'
									: scope.row.sex == '1'
									? 'danger'
									: 'info'
							"
						>
							{{
								scope.row.sex == "0" ? "男" : scope.row.sex == "1" ? "女" : "未知"
							}}</el-tag
						>
					</template>
				</el-table-column>
				<el-table-column
					prop="status"
					label="状态"
					v-if="$Tool.findEle('状态', checkedColumns)"
				>
					<template slot-scope="scope">
						<el-switch
							v-model="scope.row.status"
							@click.native="changeStatus(scope.row)"
							active-value="0"
							inactive-value="1"
						>
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column
					prop="createTime"
					label="创建时间"
					v-if="$Tool.findEle('创建时间', checkedColumns)"
				>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-row>
							<el-button
								@click.native.prevent="updateOne(scope.row)"
								type="text"
								icon="el-icon-scissors"
								size="small"
							>
								修改
							</el-button>
							<el-button
								@click.native.prevent="removeOne(scope.row.userId)"
								type="text"
								icon="el-icon-delete-solid"
								size="small"
							>
								删除
							</el-button>
							<el-popover placement="bottom" width="80" trigger="hover">
								<el-button
									type="text"
									icon="el-icon-search"
									size="small"
									@click="updatePass(scope.row)"
								>
									修改密码
								</el-button>

								<el-button
									slot="reference"
									type="text"
									icon="el-icon-d-arrow-right"
									size="small"
								>
									更多
								</el-button>
							</el-popover>
						</el-row>
					</template>
				</el-table-column>
			</el-table>
		</el-row>

		<el-row type="flex" justify="center" style="padding-top: 20px">
			<el-col :span="6">
				<el-pagination
					background
					@size-change="handlePageSize"
					@current-change="handlePage"
					:current-page="searchForm.page"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="searchForm.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="listTotal"
				>
				</el-pagination>
			</el-col>
		</el-row>

		<el-dialog
			:title="dialogTitle"
			:visible.sync="showDialog"
			:before-close="closeDialog"
			width="45%"
		>
			<el-form
				:model="submitForm"
				:rules="submitRules"
				ref="submitForm"
				label-width="6.25rem"
				inline
				class="submit-form"
			>
				<el-form-item
					v-if="dialogTitle == '新增用户'"
					label="邀请码"
					prop="invitationCode"
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.invitationCode"
						placeholder="邀请码"
					></el-input>
				</el-form-item>
				<el-form-item label="用户昵称" prop="nickname" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.nickname"
						placeholder="用户昵称(2-20位)"
					></el-input>
				</el-form-item>
				<el-form-item label="手机号码" prop="phone" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.phone"
						placeholder="请输入手机号码"
					></el-input>
				</el-form-item>
				<el-form-item label="用户名称" prop="username" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.username"
						placeholder="用户名称(2-20位)"
					></el-input>
				</el-form-item>
				<el-form-item
					label="密码"
					prop="password"
					required
					class="form-item"
					v-if="dialogTitle == '新增用户'"
				>
					<el-input
						show-password
						clearable
						v-model="submitForm.password"
						placeholder="密码长度(5-20位)"
					></el-input>
				</el-form-item>
				<el-form-item label="用户性别" prop="sex" class="form-item">
					<el-select v-model="submitForm.sex" placeholder="性别" clearable>
						<el-option
							v-for="item in sexOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="邮箱" prop="email" class="form-item">
					<el-input
						clearable
						v-model="submitForm.email"
						placeholder="请输入邮箱"
					></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="status" class="form-item">
					<el-radio-group v-model="submitForm.status">
						<el-radio label="0">正常</el-radio>
						<el-radio label="1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="备注" prop="remark" class="form-item">
					<el-input
						class="form-textarea"
						type="textarea"
						clearable
						v-model="submitForm.remark"
						placeholder="请输入内容"
						maxlength="300"
						show-word-limit
						:rows="4"
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeDialog">取 消</el-button>
				<el-button type="primary" @click="submit(dialogTitle)">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { submitRules } from "@/utils/rules/user"
import {
	getAllUser,
	updatePass,
	updateUser,
	createUser,
	removeUser,
	updateUserStatus,
	checkInviCode,
} from "@/api/system/user"
import UserUtil from "@/utils/user-util"
import { sexOptions, columns } from "@/constants/user"
import { statusOptions } from "@/constants"
export default {
	name: "FrontUser",
	data() {
		return {
			showDialog: false,
			dialogTitle: "",

			checkedColumns: columns,
			columns: columns,
			showHidCol: false,
			showSearch: true,
			searchForm: {
				username: "",
				phone: "",
				status: "",
				createTimes: [],
				page: 1,
				pageSize: 10,
			},
			statusOptions: statusOptions,
			sexOptions: sexOptions,
			list: [
				{
					userId: 1,
					username: "admin",
					nickname: "管理员吧",
					phone: "15069860202",
					status: "0",
					createTime: "2023-20-14 8:20:30",
				},
			],
			listTotal: 0,

			checkIds: [],
			checkedItems: [],

			submitForm: {
				password: "",
				username: "",
				nickname: "",
				email: "",
				status: "",
				remark: "",
				sex: "",
				phone: "",
				invitationCode: "",
			},
		}
	},
	computed: {
		submitRules,
	},

	mounted() {
		this.get()
	},

	methods: {
		search() {
			this.get()
		},
		create() {
			this.openDialog("新增用户")
		},
		update() {
			this.openDialog("修改用户")
			this.$nextTick(() => {
				this.submitForm = { ...this.checkedItems[0] }
			})
		},
		async get() {
			let search = { ...this.searchForm }
			if (search.createTimes.length !== 0) {
				search.beginTime = search.createTimes[0]
				search.endTime = search.createTimes[1]
				delete search.createTimes
			}
			let res = await getAllUser(this.$Tool.removeNullFiled(search))
			if (res.code == 200) {
				this.list = res.data
				this.listTotal = res.total
			}
		},

		openDialog(title) {
			this.showDialog = true
			this.dialogTitle = title
		},

		closeDialog() {
			this.resetForm("submitForm")
			this.showDialog = false
			this.dialogTitle = ""
		},

		async submit(title) {
			if (this.checkForm(this, "submitForm")) {
				if (title == "新增用户") {
					this.submitCreate(title)
				} else if (title == "修改用户") {
					this.submitUpdate(title)
				}
			}
		},
		changeStatus(item) {
			let { userId, status } = item
			let str = status == "1" ? "禁用" : "启用"
			this.handConfirm(
				str,
				userId,
				async () => {
					let res = await updateUserStatus({ userId, status })
					if (res.code == 200) {
						this.refresh()
					} else {
						item.status = status == "1" ? "0" : "1"
					}
				},
				() => {
					item.status = status == "1" ? "0" : "1"
				}
			)
		},
		async submitUpdate(title) {
			let res = await updateUser(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeDialog()
			} else {
				this.openDialog(title)
			}
		},
		async submitCreate(title) {
			let { invitationCode } = this.submitForm
			if (invitationCode) {
				let end = await checkInviCode(this.submitForm)
				if (end) {
					this.confirm(
						this.$confirm,
						"您后台有账户,是否将数据同步的前台?",
						() => {
							this.submitAdd(title)
						},
						() => {
							this.submitForm.invitationCode = ""
							this.submitAdd(title)
						}
					)
				}
				return
			} else {
				this.submitAdd(title)
			}
		},
		async submitAdd(title) {
			let res = await createUser(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeDialog()
			} else {
				this.openDialog(title)
			}
		},
		async checkInviCode({ invitationCode }) {
			let res = await checkInviCode({ invitationCode })
			if (res.code == 200) {
				return true
			}
			return false
		},
		updatePass({ username, password }) {
			this.prompt(
				{
					func: this.$prompt,
					text: `请输入${username}的新密码,格式为5-20位的任意字符`,
					errMes: "密码格式不正确",
				},
				UserUtil.verifyPassword,
				async ({ value }) => {
					let res = await updatePass({ password, newPassword: value })
					if (res.code == 200) {
						this.refresh()
					}
				}
			)
		},
		remove() {
			let userIds = this.checkIds
			this.handConfirm("删除", userIds, async () => {
				let res = await removeUser({ userIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		refresh() {
			this.get()
		},
		updateOne(item) {
			this.submitForm = { ...item }
			this.openDialog("修改用户")
		},
		removeOne(userId) {
			this.handConfirm("删除", userId, async () => {
				let userIds = [userId]
				let res = await removeUser({ userIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		resetForm(formName) {
			this.$Tool.objEmptyStr(this[formName], "page", "pageSize")
			this.$refs[formName].resetFields()
		},

		handMulSelect(list) {
			this.checkIds = list.map((item) => item.userId)
			this.checkedItems = list
		},
		handlePageSize(val) {
			this.searchForm.pageSize = val
			this.refresh()
		},
		handlePage(val) {
			this.searchForm.page = val
			this.refresh()
		},

		handConfirm(text, data, success, error = () => {}) {
			this.confirm(
				this.$confirm,
				`您是否确认${text}用户编号为"${this.$Tool.handlerLongStr(
					data.toString()
				)}"的数据项`,
				success,
				error
			)
		},
	},
}
</script>

<style lang="scss" scoped></style>
